<?php 

class Channel {
	
	private $channelId;
	
	//private $messageQueue;
	
	private $options;
	
	function __construct($channelId) {
		$this->channelId = $channelId;
		
		//$this->messageQueue = msg_get_queue("141288");
	}
	
	public static function getInstance($channel_num) {		
		return new Channel($channel_num);
	}
	
	public static function createChannel() {
		session_start();
		
		$channelId = 0;
		
		if(!isset($_SESSION['channels'])) {
			$channelId = rand(100, 999);
			$_SESSION['channels'] = $channelId;
		} else {
			$channelId = $_SESSION['channels'];	
		}
		
		return new Channel($channelId);
	}

	public function getId() {
		return $this->channelId;
	}
	
	public function getOptions() {
		return $this->options;
	}
	
	public function setOptions($options) {
		$this->options = $options;
	}
	
	public function sendMessage($message, $to) {
		//$error;
		//
		$this->writeMessage($message, $to);
	}
	
	public function getMessage($timestamp) {
		$message;

		$numTries = 10;
		
		do {
			$message = $this->readMessage($timestamp);
			
			if(connection_aborted()) {
				break;
			}
			
			if(empty($message) && $numTries > 0) {
				$numTries--;
				sleep(2);
			}
		} while(empty($message) && $numTries > 0);
		
		return $message;
	}
	
	private function writeMessage($message, $to) {
		/*
		$error;
		msg_send($this->messageQueue, $to, $message, TRUE, FALSE, $error);
		*/
		$conn = $this->options['db_connection'];
		
		$query = sprintf("INSERT INTO channels (channel_id, msg, timestamp) VALUES (%d, '%s', %d)",
			$to, 
			base64_encode(json_encode($message)),
			microtime(TRUE)*1000);
			
		$result = mysql_query($query, $conn) or die(mysql_error($conn));
	}
	
	private function readMessage($timestamp) {
		
		$conn = $this->options['db_connection'];
		
		$query = "SELECT channel_id, msg, timestamp FROM channels WHERE" .
				  " channel_id = ".$this->channelId . " ORDER BY id;";
		
		$result = mysql_query($query, $conn);
		
		$messages = array();
		
		while($row = mysql_fetch_array($result)) {
			array_push($messages, array("timestamp" => $row[2], "msg" => json_decode(base64_decode($row[1]))));
		}
		
		//Delete query
		$query = "DELETE FROM channels WHERE channel_id = ".$this->channelId;
		mysql_query($query, $conn);
		
		/*$messages;
		$type;
		$error;
		
		msg_receive($this->messageQueue, $this->channelId, $type, 1024, $messages, TRUE, MSG_IPC_NOWAIT, $error);
		*/
		
		return $messages;
	}
	
   
}



?>